package com.infinit.easyreader.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.infinit.easyreader.entity.Book;
import com.infinit.easyreader.entity.Bookmark;
import com.infinit.easyreader.utils.Consts;

import java.util.ArrayList;
import java.util.List;

/**
 * 包含类 : com.infinit.easyreader.dao
 * 作用：操作bookmark数据库
 * Created by rzy on 2016/2/18.
 */
public class BookmarkDao extends SQLiteOpenHelper implements Consts {
    private String tableName = "bookmarks";
    private SQLiteDatabase database;

    public BookmarkDao(Context context) {
        super(context, dataBaseName, null, 1);
        database = getWritableDatabase();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }


    /**
     * 作用：获取当前书籍的所有书签
     *
     * @param book 需要查询书籍的对象
     * @return 所有书签的集合
     */

    public List<Bookmark> findAllBookmark(Book book) {
        String[] columns = {
                "_id",
                "book_id",
                "position",
                "quote"
        };
        String selection = "book_id=?";
        Cursor cursor = database.query(tableName, columns, selection,
                new String[]{book.getBookId() + ""}, null, null, null);
        if (cursor.getColumnCount() == 0) {
            return null;
        }
        cursor.moveToFirst();
        List<Bookmark> marks = new ArrayList<>();
        while (!cursor.isAfterLast()) {
            Bookmark bookmark = new Bookmark();
            bookmark.setId(cursor.getInt(0));
            bookmark.setBook_id(cursor.getInt(1));
            bookmark.setPosition(cursor.getLong(2));
            bookmark.setQuote(cursor.getString(3));
            marks.add(bookmark);
            cursor.moveToNext();
        }
        cursor.close();
        return marks;
    }

    /**
     * 作用：添加书签
     *
     * @param mark bookmark对象
     */

    public void insertBookmark(Bookmark mark) {
        ContentValues values = new ContentValues();
        values.put("book_id", mark.getBook_id());
        values.put("position", mark.getPosition());
        values.put("quote", mark.getQuote());
        database.insertWithOnConflict(tableName, null, values, SQLiteDatabase.CONFLICT_IGNORE);
    }

    /**
     * 作用：删除书签
     */

    public void deleteBookmark(Bookmark bookmark) {

        database.delete(tableName, "_id=?", new String[]{bookmark.getId() + ""});
    }


    /**
     * 根据进度来删除书签
     */

    public void deleteBookMarkAtPosition(int position) {

        database.delete(tableName, "position=?", new String[]{position + ""});
    }


    /**
     * 销毁数据库链接
     */

    public void onDestroy() {

        database.close();

    }


}
